<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/promiseajax.js"></script>
    <script src="./js/cookie.js"></script>
</head>

<body>
    <form action="">
        账号:<input type="text" name="uername">
        <br>
        密码:<input type="password" name="password">
        <br>
        <input type="submit">
    </form>
</body>
<script>
    var form = document.querySelector('form')
    form.onsubmit = function () {
        var ipts = document.querySelectorAll('input')
        var username = ipts[0].value
        var password = ipts[1].value
        request({
            url: '/api/users/login',
            method: 'post',
            data: {
                username,
                password
            }
        }).then((res) => {
            // console.log(res);
            let { error_code, msg } = res
            alert(msg)
            if (error_code === 0) {
                setCookie('username', username, 7200)

                setCookie('userid', res.data.userid, 7200 + 3600)
                localStorage.setItem('token', res.data.token)
                // 判断是否有存储过的地址，有就跳到存储的地址，没有就跳到首页
                var url = localStorage.getItem('url')
                if (url) {
                    localStorage.removeItem('url')
                    location.href = url
                } else {
                    location.href = '/'
                }
                
            }
        })
        return false
    }
</script>

</html>